from threading import *
import wx
from Carry import EVT_RESULT,ResultEvent
from os import listdir, popen
from string import join,split,strip

# Thread class that executes processing
class NetStatThread(Thread):
    """Worker Thread Class."""
    def __init__(self, notify_window):
        """Init Worker Thread Class."""
        Thread.__init__(self)
        self._notify_window = notify_window
        self.start()

    def run(self):
        """Run Worker Thread."""
        connections = self.connstat()
        wx.PostEvent(self._notify_window, ResultEvent({'type':4,'connections':connections})) 

    def connstat(self):
        netstat=popen("netstat -n -A inet")
        stats = join(netstat.readlines(),'')[82:]
        stats = split(`stats`,'\\n')
        
        i = 0
        etb_connections = []
        while i < len(stats)-1:
            try:
                proto = stats[i][0:8].strip()
                status      = stats[i][68:].strip()
                ip_src    = split(split(stats[i][9:],':')[0],' ')[-1]
                port_src  = split(split(stats[i][9:],':')[1],' ')[0]
                ip_dest   = split(split(stats[i][9:],':')[1],' ')[-1]
                port_dest = split(split(stats[i][9:],':')[2],' ')[0]
                etb_connections.append({'PROTO':proto,'STATUS':status,'SRC':ip_src,'SRC_PORT':port_src,'DEST':ip_dest,'DEST_PORT':port_dest})
            except:
                pass
            i+=1

        return etb_connections